package com.cskaoyan.catmall.service.Impl;

import com.cskaoyan.catmall.config.keyword.DateUtils;
import com.cskaoyan.catmall.dao.WxAddressDao;
import com.cskaoyan.catmall.model.bo.SaveAddressBo;
import com.cskaoyan.catmall.model.pojo.MarketAddress;
import com.cskaoyan.catmall.model.vo.AddressVo;
import com.cskaoyan.catmall.model.vo.GetAddressListVo;
import com.cskaoyan.catmall.service.WxAddressService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 创建日期: 2022/01/10 20:24
 *
 * @author WangZhe
 * 备注:
 */
@Service
public class WxAddressServiceImpl implements WxAddressService {

    @Autowired
    WxAddressDao wxAddressDao;

    @Override
    public GetAddressListVo getList(Integer userId) {
        Integer page = 1;
        Integer limit = 10;
        PageHelper.startPage(page, limit);

        List<AddressVo> list = wxAddressDao.getList(userId);

        PageInfo<AddressVo> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return GetAddressListVo.data(total, pages, limit, page, list);
    }

    @Override
    public AddressVo getDetail(Integer addressId) {

        return wxAddressDao.getDetail(addressId);
    }

    @Override
    public Integer saveAddress(Integer userId, SaveAddressBo saveAddressBo) {

        MarketAddress pojo = new MarketAddress();

        pojo.setId(saveAddressBo.getId());
        pojo.setName(saveAddressBo.getName());
        pojo.setProvince(saveAddressBo.getProvince());
        pojo.setCity(saveAddressBo.getCity());
        pojo.setCounty(saveAddressBo.getCounty());
        pojo.setAddressDetail(saveAddressBo.getAddressDetail());
        pojo.setAreaCode(saveAddressBo.getAreaCode());
        pojo.setTel(saveAddressBo.getTel());
        pojo.setIsDefault(saveAddressBo.getIsDefault());
        pojo.setUpdateTime(DateUtils.formatDate(new Date()));
        pojo.setDeleted(false);

        if (pojo.getIsDefault())
            wxAddressDao.updateIsDefaultById(pojo.getId());


        Integer affectedRows = null;

        if (pojo.getId() == 0){
            pojo.setUserId(userId);
            pojo.setAddTime(pojo.getUpdateTime());
            affectedRows = wxAddressDao.insertAddress(pojo);
        } else
            affectedRows = wxAddressDao.saveAddress(pojo);
        if (affectedRows == 1)
            return saveAddressBo.getId();
        return 500;
    }

    @Override
    public void deleteAddress(Integer id) {

        wxAddressDao.deleteAddress(id);
    }
}
